// 修改 src/stores/user.js，增加调试信息
import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
  state: () => ({
    role: null,
    userInfo: null
  }),
  getters: {
    getRole: (state) => {
      console.log('获取角色:', state.role);
      return state.role;
    },
    getUserInfo: (state) => state.userInfo
  },
  actions: {
    setRole(newRole) {
      console.log('设置角色:', newRole);
      this.role = newRole;
    },
    setUserInfo(userInfo) {
      console.log('设置用户信息:', userInfo);
      this.userInfo = userInfo;
      // 同时设置角色
      if (userInfo && typeof userInfo.role !== 'undefined') {
        const role = userInfo.role === 0 ? 'admin' : 'student';
        this.setRole(role);
      }
    },
    initRole() {
      const loginUser = localStorage.getItem('loginUser');
      if (loginUser) {
        try {
          const user = JSON.parse(loginUser);
          console.log('从localStorage读取用户信息:', user);
          
          // 设置用户信息
          this.userInfo = user;
          
          // 确保role字段存在且有效
          if (typeof user.role !== 'undefined') {
            const role = user.role === 0 ? 'admin' : 'student';
            console.log('初始化角色:', role, '(原始值:', user.role, ')');
            this.role = role;
          } else {
            console.warn('用户信息中缺少role字段');
            this.role = null;
          }
        } catch (error) {
          console.error('解析localStorage用户信息失败:', error);
          this.role = null;
          this.userInfo = null;
        }
      } else {
        console.log('localStorage中没有用户信息');
        this.role = null;
        this.userInfo = null;
      }
    },
    clearUser() {
      console.log('清除用户信息');
      this.role = null;
      this.userInfo = null;
      localStorage.removeItem('loginUser');
    }
  }
});